<template>
    <div class="main-box">
        <div class="category-box box">
            <div class="box-header">{{ $t('course.category.index.category_box.tit') }}</div>
            <div class="box-body" v-loading="categoryLoading">
                <div class="btn-list">
                    <el-button color="#f06423" icon="Plus" @click="goPage('/console/course/category/create')">{{ $t('course.category.index.category_box.btn_text_1') }}</el-button>
                </div>
                <el-tree :data="categoryList" node-key="id" :props="defaultProps" default-expand-all :expand-on-click-node="false" draggable :allow-drop="allowDrop" @node-drop="handleNodeDrop">
                    <template #default="{ node, data }">
                        <div class="custom-tree-node">
                            <span>{{ data.name }}</span>
                            <div class="tools-box">
                                <el-icon size="18" @click="goPage(`/console/course/category/create?parentId=${data.id}`)"><Plus /></el-icon>
                                <el-icon size="18" @click="deleteCategoryHandle(data)"><Delete /></el-icon>
                                <el-icon size="18" @click="goPage('courseCategoryEdit', { id: data.id })"><Edit /></el-icon>
                                <el-icon size="18" @click="viewCourseHandler(data)"><View /></el-icon>
                            </div>
                        </div>
                    </template>
                </el-tree>
            </div>
        </div>

        <div class="course-box box">
            <div class="box-header">{{ checkedCategory?.name || $t('course.category.index.course_box.tit') }}</div>
            <div class="box-body" v-loading="courseLoading">
                <div class="btn-list">
                    <el-input v-model="searchKey" :placeholder="$t('course.category.index.course_box.inp_placeholder')"></el-input>
                    <el-button icon="Search" color="#f06423" @click="getCourseList" />
                    <el-button color="#f06423" icon="Plus" @click="goPage(`/console/course/create${checkedCategory?.id ? `?categoryId=${checkedCategory?.id}` : ''}`)">{{
                        $t('course.category.index.course_box.btn_text_1')
                    }}</el-button>
                    <el-button color="#f06423" icon="Delete" v-if="checkedCourse.length" @click="deleteCourseHandle(undefined)">{{ $t('course.category.index.course_box.btn_text_2') }}</el-button>
                </div>

                <el-checkbox-group v-model="checkedCourse" v-if="courseList.length">
                    <div class="course-list">
                        <div class="course-item" v-for="course in courseList" :key="course.id">
                            <el-checkbox :label="course.id" :value="course.id" class="course-name">
                                {{ course.name }}
                            </el-checkbox>
                            <div class="tools-box">
                                <el-icon size="18" @click="deleteCourseHandle(course)"><Delete /></el-icon>
                                <el-icon size="18" @click="goPage('courseEdit', { courseId: course.id })"><Edit /></el-icon>
                                <el-icon size="18" @click="goPage('courseNull', { courseId: course.id })"><View /></el-icon>
                                <el-icon size="18" @click="copyClassAction(course.id)"><CopyDocument /></el-icon>
                            </div>
                        </div>
                    </div>
                </el-checkbox-group>
                <el-empty v-else image=" " :description="$t('golbal.empty_desc')" />

                <div class="pagination-box">
                    <el-pagination
                        size="small"
                        background
                        v-model:page-size="pagination.limit"
                        v-model:current-page="pagination.page"
                        layout="sizes, prev, pager, next"
                        :total="pagination.total"
                        :page-sizes="[10, 20, 50, 100]"
                        class="mt-4"
                        :hide-on-single-page="true"
                        @size-change="getCourseList"
                        @current-change="getCourseList"
                    />
                </div>
            </div>
        </div>
    </div>

    <el-dialog v-model="deleteDialog" :title="$t('course.category.index.dialog_tit')" width="400" class="mobile-dialog">
        <p>{{ deleteText }}</p>
        <template #footer>
            <el-button color="#f06423" @click="confirmHandle" :loading="dialogLoading">{{ $t('golbal.btn_text_4') }}</el-button>
            <el-button color="#435764" @click="deleteDialog = false" :loading="dialogLoading">{{ $t('golbal.btn_text_3') }}</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'

import CourseCategoryService from '@/api/courseCategory'
import type { CourseCategoryItem } from '@/types/courseCategory'

import CourseService from '@/api/course'
import type { CourseItem } from '@/types/course'

import { goPage } from '@/utils/global'
import type { Pagination } from '@/types/global'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()
const defaultProps = {
    id: 'id',
    children: 'children',
    label: 'name',
}
const allowDrop = (draggingNode: any, dropNode: any, type: 'prev' | 'inner' | 'next') => {
    return draggingNode.parent?.data.id === dropNode.parent?.data.id && type !== 'inner'
}
const handleNodeDrop = (draggingNode: any) => {
    // 获取被拖拽节点的父节点
    const parent_id = draggingNode.data.parent_id
    let currentCate: CourseCategoryItem[] = categoryList.value
    if (parent_id !== 0) currentCate = categoryList.value.find(cate => cate.id === parent_id)?.children || []

    if (currentCate.length) {
        categoryLoading.value = true
        CourseCategoryService.sort(currentCate.map((cate, index) => ({ id: cate.id, sort_order: index + 1 }))).finally(() => {
            setTimeout(() => {
                categoryLoading.value = false
            }, 1000)
        })
    }
}

// 課程類別
const categoryList = ref<CourseCategoryItem[]>([])
const checkedCategory = ref<CourseCategoryItem>()
const deleteCategoryId = ref<number>()
const categoryLoading = ref(false)
function getCategoryList() {
    categoryLoading.value = true
    CourseCategoryService.list()
        .then(res => {
            categoryList.value = res.items
            courseLoading.value = true
            getCourseList()
        })
        .finally(() => {
            setTimeout(() => {
                categoryLoading.value = false
            }, 1000)
        })
}
const deleteCategoryHandle = (category: CourseCategoryItem) => {
    deleteCategoryId.value = category.id
    deleteDialog.value = true
    deleteText.value = `${t('course.category.index.dialog_con_1')} ${category.name} ${t('course.category.index.dialog_con_2')}`
    typeDialog.value = 'category'
}
const viewCourseHandler = (category: CourseCategoryItem) => {
    checkedCategory.value = category
    getCourseList()
}

// 課程
const courseList = ref<CourseItem[]>([])
const checkedCourse = ref<number[]>([])
const courseLoading = ref(false)
const searchKey = ref<string>('')
const pagination = ref<Pagination>({
    page: 1,
    limit: 10,
    total: 10,
})
function getCourseList() {
    courseLoading.value = true
    CourseService.list(pagination.value, checkedCategory.value?.id, searchKey.value)
        .then(res => {
            courseList.value = res.items
            pagination.value.total = res.pagination.total
        })
        .finally(() => {
            setTimeout(() => {
                courseLoading.value = false
            }, 1000)
        })
}
const deleteCourseHandle = (course?: CourseItem) => {
    if (course) {
        checkedCourse.value = [course.id]
        deleteText.value = `${t('course.category.index.dialog_con_3')} ${course.name} ${t('course.category.index.dialog_con_4')}`
    } else {
        deleteText.value = t('course.category.index.dialog_con_5')
    }
    deleteDialog.value = true
    typeDialog.value = 'course'
}

// 刪除彈窗
const deleteDialog = ref(false)
const deleteText = ref(t('course.category.index.dialog_con_5'))
const typeDialog = ref<'category' | 'course'>('category')
const dialogLoading = ref(false)
const confirmHandle = () => {
    dialogLoading.value = true
    switch (typeDialog.value) {
        case 'category':
            if (!deleteCategoryId.value) break
            CourseCategoryService.delete(deleteCategoryId.value)
                .then(() => {
                    getCategoryList()
                    deleteDialog.value = false
                    deleteCategoryId.value = undefined
                })
                .finally(() => {
                    dialogLoading.value = false
                })
            break
        case 'course':
            CourseService.delete(checkedCourse.value)
                .then(() => {
                    getCourseList()
                    deleteDialog.value = false
                    checkedCourse.value = []
                })
                .finally(() => {
                    dialogLoading.value = false
                })
            break
        default:
            dialogLoading.value = false
            break
    }
}
// 复制课程
function copyClassAction(courseId: number) {
    dialogLoading.value = true
     CourseService.copyClass(courseId)
        .then(() => {
            getCourseList()
        })
        .finally(() => {
            dialogLoading.value = false
        })
}


onMounted(() => {
    getCategoryList()
})
</script>

<style lang="less" scoped>
@import '@/assets/styles/variable.less';
.main-box {
    display: flex;
    gap: 30px;
    width: 100%;
    flex-direction: row;
    @media screen and (max-width: @lPhone) {
        flex-direction: column;
    }
    .box {
        width: calc(50% - 15px);
        background-color: #f6f7f7;

        display: flex;
        flex-direction: column;
        @media screen and (max-width: @lPhone) {
            width: 100%;
        }
        .box-header {
            border-bottom: 1px solid #e3e3e3;
            padding: 10px 20px;
            font-size: 18px;
            font-weight: bold;
            color: #000;
            flex-shrink: 0;
        }

        .box-body {
            margin: 20px;
            padding: 10px 0;
            flex-grow: 1;
            background-color: #fff;

            .btn-list {
                padding: 0 10px 20px;
                display: flex;
                align-items: center;
                justify-content: flex-end;
            }
        }
    }

    .el-tree {
        --el-tree-node-content-height: 34px;
    }

    .custom-tree-node {
        display: flex;
        align-items: center;
        justify-content: space-between;

        width: 100%;
    }

    .tools-box {
        padding-right: 10px;
        display: flex;
        align-items: center;
        gap: 10px;

        .el-icon {
            cursor: pointer;
            color: #000;

            &:hover {
                color: #f06423;
            }
        }
    }

    .course-list {
        .course-item {
            border-bottom: 1px solid #e3e3e3;
            padding: 10px 20px;
            background-color: #fff;
            font-size: 15px;
            color: #000;

            .tools-box {
                margin-top: 10px;
                justify-content: flex-end;
            }
        }
    }

    :deep(.el-empty) {
        --el-empty-padding: 30px 0 0;
        --el-empty-description-margin-top: 0;

        .el-empty__image {
            display: none;
        }
    }

    .pagination-box {
        padding-right: 10px;
    }
}
</style>
